/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.app.service.collect.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.collect.CereBuyerCollectDAO;
import com.shop.cereshop.app.dao.product.CereShopProductDAO;
import com.shop.cereshop.app.dao.recommend.CereRecommendTrendsDAO;
import com.shop.cereshop.app.page.collect.CollectProduct;
import com.shop.cereshop.app.page.collect.CollectShop;
import com.shop.cereshop.app.page.product.ProductDetailSimple;
import com.shop.cereshop.app.page.recommend.RecommendPageVO;
import com.shop.cereshop.app.param.collect.CollectGetAllParam;
import com.shop.cereshop.app.param.collect.CollectIdParam;
import com.shop.cereshop.app.param.collect.CollectParam;
import com.shop.cereshop.app.param.recommend.RecommendLikeDTO;
import com.shop.cereshop.app.service.collect.CereBuyerCollectService;
import com.shop.cereshop.app.tencent.im.service.MsgService;
import com.shop.cereshop.app.utils.RedisUtil;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.collect.CereBuyerCollect;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.recommend.CereRecommendTrends;
import com.shop.cereshop.commons.enums.RedisEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.tencent.im.enums.notice.SysNoticeTargetTypeEnum;
import com.shop.cereshop.commons.tencent.im.enums.notice.SysNoticeTypeEnum;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class CereBuyerCollectServiceImpl implements CereBuyerCollectService {

    @Value("${time.format}")
    private String time;

    @Autowired
    private CereBuyerCollectDAO cereBuyerCollectDAO;
    @Autowired
    private CereShopProductDAO cereShopProductDAO;
    @Autowired
    private CereRecommendTrendsDAO cereRecommendTrendsDAO;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MsgService msgService;

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void collect(CollectParam param, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        if (!EmptyUtils.isEmpty(param.getProductId())) {
            //收藏商品,查询当前收藏该商品数据
            CereBuyerCollect cereBuyerCollect = cereBuyerCollectDAO.findByUserProduct(user.getBuyerUserId(), param.getProductId());
            if (cereBuyerCollect != null) {
                //收藏过,设置状态
                if (IntegerEnum.YES.getCode().equals(cereBuyerCollect.getState())) {
                    //如果是已收藏,改为未收藏
                    cereBuyerCollect.setState(IntegerEnum.NO.getCode());
                    cereBuyerCollect.setIsRead(0);
                } else {
                    //反之
                    cereBuyerCollect.setState(IntegerEnum.YES.getCode());
                    cereBuyerCollect.setIsRead(0);
                }
                cereBuyerCollect.setSalesType(param.getSalesType());
                cereBuyerCollect.setUpdateTime(time);
                cereBuyerCollectDAO.updateByPrimaryKeySelective(cereBuyerCollect);
            } else {
                //第一次收藏
                cereBuyerCollect = new CereBuyerCollect();
                cereBuyerCollect.setBuyerUserId(user.getBuyerUserId());
                cereBuyerCollect.setProductId(param.getProductId());
                cereBuyerCollect.setCreateTime(time);
                cereBuyerCollect.setCollectType(IntegerEnum.BUYER_COLLECT_PRODUCT.getCode());
                cereBuyerCollect.setState(IntegerEnum.YES.getCode());
                cereBuyerCollect.setSelected(IntegerEnum.NO.getCode());
                cereBuyerCollect.setIsRead(0);
                cereBuyerCollect.setSalesType(param.getSalesType());
                cereBuyerCollectDAO.insert(cereBuyerCollect);
            }

            // todo 发送系统通知给店铺所有者，有人收藏了商品
//            Long shopUserId = null;
//            msgService.sendNotice(shopUserId, SysNoticeTypeEnum.COLLECT.getCode(), SysNoticeTargetTypeEnum.PRODUCT.getCode(),
//                    String.valueOf(param.getProductId()), user.getBuyerUserId(), user.getName());

        } else if (!EmptyUtils.isEmpty(param.getShopId())) {
            //收藏店铺,,查询当前收藏该店铺数据
            CereBuyerCollect cereBuyerCollect = cereBuyerCollectDAO.findByUserShopId(user.getBuyerUserId(), param.getShopId());
            if (cereBuyerCollect != null) {
                //收藏过,设置状态
                if (IntegerEnum.YES.getCode().equals(cereBuyerCollect.getState())) {
                    //如果是已收藏,改为未收藏
                    cereBuyerCollect.setState(IntegerEnum.NO.getCode());
                    cereBuyerCollect.setIsRead(0);
                } else {
                    //反之
                    cereBuyerCollect.setState(IntegerEnum.YES.getCode());
                    cereBuyerCollect.setIsRead(0);
                }
                cereBuyerCollect.setSalesType(param.getSalesType());
                cereBuyerCollect.setUpdateTime(time);
                cereBuyerCollectDAO.updateByPrimaryKeySelective(cereBuyerCollect);
            } else {
                //第一次收藏
                cereBuyerCollect = new CereBuyerCollect();
                cereBuyerCollect.setBuyerUserId(user.getBuyerUserId());
                cereBuyerCollect.setShopId(param.getShopId());
                cereBuyerCollect.setCreateTime(time);
                cereBuyerCollect.setCollectType(IntegerEnum.BUYER_COLLECT_SHOPID.getCode());
                cereBuyerCollect.setState(IntegerEnum.YES.getCode());
                cereBuyerCollect.setSelected(IntegerEnum.NO.getCode());
                cereBuyerCollect.setIsRead(0);
                cereBuyerCollect.setSalesType(param.getSalesType());
                cereBuyerCollectDAO.insert(cereBuyerCollect);
            }

            // todo 发送系统通知给店铺所有者，有人收藏了店铺
//            Long shopUserId = null;
//            msgService.sendNotice(shopUserId, SysNoticeTypeEnum.COLLECT.getCode(), SysNoticeTargetTypeEnum.SHOP.getCode(),
//                    String.valueOf(param.getShopId()), user.getBuyerUserId(), user.getName());

        }
        //        收藏动态
        else if (!EmptyUtils.isEmpty(param.getRecommendId())) {
//            判断该用户是可以收藏动态
            if (user.getIfAllowOther()==0) {
                throw new CoBusinessException(CoReturnFormat.NOT_ALLOW_COLLECT_DYNAMIC);
            }
            //判断动态是否存在
            CereRecommendTrends recommendTrends = cereRecommendTrendsDAO.selectRecommendIdIsExist(param.getRecommendId());
            if (recommendTrends == null) {
                throw new CoBusinessException(CoReturnFormat.DYNAMIC_TYPE_NOT_EXIST);
            }
            //收藏动态,查询当前收藏该动态数据
            CereBuyerCollect cereBuyerCollect = cereBuyerCollectDAO.findByUserDaynamicId(user.getBuyerUserId(), param.getRecommendId());
            if (cereBuyerCollect != null) {
                //收藏过,设置状态
                if (IntegerEnum.YES.getCode().equals(cereBuyerCollect.getState())) {
                    //如果是已收藏,改为未收藏
                    cereBuyerCollect.setState(IntegerEnum.NO.getCode());
                    redisUtil.decrementLike(RedisEnum.USER_COLLECT_KEY.getKey(), String.valueOf(param.getRecommendId()));
                    cereBuyerCollect.setIsRead(0);
                } else {
                    //反之
                    cereBuyerCollect.setState(IntegerEnum.YES.getCode());
                    cereBuyerCollect.setIsRead(0);
                    redisUtil.incrementLike(RedisEnum.USER_COLLECT_KEY.getKey(), String.valueOf(param.getRecommendId()));
                }
                cereBuyerCollect.setUpdateTime(time);
                cereBuyerCollectDAO.updateByPrimaryKeySelective(cereBuyerCollect);
            } else {
                //第一次收藏动态
                cereBuyerCollect = new CereBuyerCollect();
                cereBuyerCollect.setBuyerUserId(user.getBuyerUserId());
                cereBuyerCollect.setRecommendId(param.getRecommendId());
                cereBuyerCollect.setCreateTime(time);
                cereBuyerCollect.setCollectType(IntegerEnum.BUYER_COLLECT_DYNAMIC.getCode());
                cereBuyerCollect.setState(IntegerEnum.YES.getCode());
                cereBuyerCollect.setSelected(IntegerEnum.NO.getCode());
                cereBuyerCollect.setIsRead(0);
                cereBuyerCollectDAO.insert(cereBuyerCollect);
                redisUtil.incrementLike(RedisEnum.USER_COLLECT_KEY.getKey(), String.valueOf(param.getRecommendId()));
            }

            // 发送系统通知给动态作者，有人收藏了动态
            msgService.sendNotice(recommendTrends.getBuyerUserId(), SysNoticeTypeEnum.COLLECT.getCode(), SysNoticeTargetTypeEnum.POSTS.getCode(),
                    String.valueOf(param.getRecommendId()), user.getBuyerUserId(), user.getName());

        }
    }



    @Override
    public CereBuyerCollect findByUserProduct(Long buyerUserId, Long productId) {
        return cereBuyerCollectDAO.findByUserProduct(buyerUserId, productId);
    }

    @Override
    public CereBuyerCollect findByUserShopId(Long buyerUserId, Long shopId) {
        return cereBuyerCollectDAO.findByUserShopId(buyerUserId, shopId);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void cancel(CollectIdParam param, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        //批量
        cereBuyerCollectDAO.cancel(param.getIds(), user.getBuyerUserId(), time);
    }

    @Override
    public void newCancel(CollectParam param, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        cereBuyerCollectDAO.newCancel(param.getProductId(),param.getShopId(), user.getBuyerUserId(), time, param.getSalesType());
    }

    @Override
    public Page getAllProduct(CollectGetAllParam param, CereBuyerUser user) throws CoBusinessException {

        if (param.getPage() == null || param.getPageSize() != null) {
            param.setPage(1);
            param.setPageSize(10);
        }

        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<CollectProduct> list = cereBuyerCollectDAO.getAllProduct(user.getBuyerUserId(), param.getSearch());
//        list.forEach(product -> {
//            ProductBo productBo = cereShopProductService.fetchProductCache(product.getShopId(), product.getProductId(), product.getSkuId(), user, false);
//            if (productBo != null) {
//                product.setActivityType(productBo.getActivityType());
//            }
//        });
        PageInfo<CollectProduct> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }


    @Override
    public Page getCollectProducts(CollectGetAllParam param, CereBuyerUser user) {

        if (param.getPage() == null || param.getPageSize() != null) {
            param.setPage(1);
            param.setPageSize(10);
        }

        PageHelper.startPage(param.getPage(), param.getPageSize());
//        List<CollectProduct> list=cereBuyerCollectDAO.getAllProduct(user.getBuyerUserId(),param.getSearch());
//        list.forEach(product -> {
//            ProductBo productBo = cereShopProductService.fetchProductCache(product.getShopId(), product.getProductId(), product.getSkuId(), user, false);
//            if (productBo != null) {
//                product.setActivityType(productBo.getActivityType());
//            }
//        });
        //查询用户收藏的商品id集合
        List<Long> productIds = cereBuyerCollectDAO.getProductIds(user.getBuyerUserId());
        List<ProductDetailSimple> list = cereShopProductDAO.findProductDetailsByShopId(null, null, null, null, null, productIds);
        PageInfo<ProductDetailSimple> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public Page<RecommendPageVO> getCollectRecommendPage(CereBuyerUser user, RecommendLikeDTO param) {
        //封装分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<RecommendPageVO> list = cereBuyerCollectDAO.getCollectRecommendPage(param.getTargetId(), param.getRecommendId(), param.getBlockedUserIds());
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(RecommendPageVO::init);
            PageInfo<RecommendPageVO> pageInfo = new PageInfo<>(list);
            return new Page<>(pageInfo.getList(), pageInfo.getTotal());
        }
        return new Page<>(Collections.emptyList(), 0);
    }

    @Override
    public Page getAllShop(CollectGetAllParam param, CereBuyerUser user) throws CoBusinessException {

        if (param.getPage() == null || param.getPageSize() != null) {
            param.setPage(1);
            param.setPageSize(10);
        }

        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<CollectShop> list = cereBuyerCollectDAO.getAllShop(user.getBuyerUserId(), param.getSearch());
        PageInfo<CollectShop> pageInfo = new PageInfo<>(list);
//        list.forEach(a -> {
//            a.setProductList(cereShopProductDAO.findRandom4ShopProducts(a.getShopId()));
//        });
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void selected(CollectIdParam param, CereBuyerUser user) throws CoBusinessException {
        //批量选中
        cereBuyerCollectDAO.updateSelected(param.getIds());
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void delete(CollectIdParam param, CereBuyerUser user) throws CoBusinessException {
        //批量删除
        cereBuyerCollectDAO.deleteByIds(param.getIds());
    }

    @Override
    public void updateBuyerData(Long buyerUserId, Long id) throws CoBusinessException {
        cereBuyerCollectDAO.updateBuyerData(buyerUserId, id);
    }

    @Override
    public int findShopCollectCount(Long shopId) {
        return cereBuyerCollectDAO.findShopCollectCount(shopId);
    }

    @Override
    public int findAllCollectCount(Long buyerUserId) {
        return cereBuyerCollectDAO.selectCount(Wrappers.<CereBuyerCollect>lambdaQuery().eq(CereBuyerCollect::getBuyerUserId, buyerUserId).eq(CereBuyerCollect::getState, IntegerEnum.YES.getCode()));
    }
}
